package com.example.common.filter;

import com.example.common.constant.SecurityConstants;
import com.example.common.util.GsonUtil;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Operators;

import java.util.function.Consumer;
import java.util.function.LongConsumer;

@Slf4j
public class ReactiveRequestContextHolder {
    public static final Class<ServerHttpRequest> CONTEXT_KEY = ServerHttpRequest.class;

    public static Mono<ServerHttpRequest> getRequest(){
        return Mono.deferContextual(context -> Mono.just(context.get(CONTEXT_KEY)));
    }

    public static Mono<Long> getUserId(){
        return Mono.deferContextual(context -> Mono.just(context.get(CONTEXT_KEY))).flatMap(request -> {
            String userInfo = request.getHeaders().getFirst(SecurityConstants.HEADER_USER_INFO);
            log.info("token have, user info : {}", userInfo);
            JsonObject jsonObject = GsonUtil.toJsonObject(userInfo);
            Long userId = jsonObject.get("userId").getAsLong();
            log.info("token have, user id : {}", userId);

            return Mono.just(userId);
        });
    }
}
